package com.yq.day72;



import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;

import java.io.IOException;

/**
 * @author 3307235355@qq.com
 * @description  自定义类加载器
 * @since 2022/07/02 09:46
 */
public class Demo01 extends ClassLoader {
    String classPath;

    public Demo01(String classPath) {
        this.classPath = classPath;
    }

    public static void main(String[] args) {

    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        //读取字节码文件 加载到内存
        Class<?> aClass =null;

        try {
            byte[] data = getData();
            //最终返回这个类的字节码文件对象
            // Class<?> aClass = defineClass();
            aClass = defineClass(name,data, 0, data.length);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return aClass;
    }

    private byte[] getData() throws IOException {
        //    按照给定的路径读取
        //    创建输入流对象
        FileInputStream in = new FileInputStream(classPath);
        //    引入一个新的输出流 ByteArraysOutputStream
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        int readCount;
        byte[] bytes = new byte[1024];
        while ((readCount=in.read(bytes))!=-1){
            out.write(bytes,0,readCount);
        }
        //获取字节数组
        byte[] bytes1 = out.toByteArray();

        out.close();
        in.close();

        return bytes1;
    }
}
